package com.oa.android.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.WorkAdapter;
import com.oa.android.entry.Work;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.XListView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


/**
 * 工作列表
 *
 * @author -zouqh
 */
public class WorkListActivity extends Activity implements OnClickListener, XListView.IXListViewListener {

    private ImageView close;
    private TextView title, searchCru,addEmil;
    private XListView listView;
    ProgressDialog dialog;
    private List<Work> emilList;
    private int page = 1;
    private int pageSize = 12;
    private int allPage = 0;
    private WorkAdapter adapter;
    private String keyword = "";
    private int type;
    public static WorkListActivity activity;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cao_gaox_activity);
        activity=this;
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        searchCru = (TextView) findViewById(R.id.searchCru);
        addEmil= (TextView) findViewById(R.id.ritgh_text);

        listView = (XListView) findViewById(R.id.listView);
        type=Integer.parseInt(getIntent().getStringExtra("type"));

        searchCru.setHint("请输入工作名称");
        if (type==1){
            url=UConstants.GET_WORK_LIST;
            title.setText("个人工作");
            addEmil.setText("新增");
            addEmil.setVisibility(View.VISIBLE);
            addEmil.setOnClickListener(this);
        }else if (type==2){
            url=UConstants.GET_DA_WORK;
            title.setText("待办工作");
        }else if (type==3){
            url=UConstants.GET_WORK_SELECT;
            title.setText("工作查询");
        }
        listView.setPullLoadEnable(true);// 向上滑动加载更多开启
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);
        listView.setFooterName("", false);
        close.setOnClickListener(this);
        searchCru.setOnClickListener(this);
        emilList = new ArrayList<>();

        adapter = new WorkAdapter(this, emilList, type);
        listView.setAdapter(adapter);
        getDate(keyword, type);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent();
                if (type==1){
                    intent.setClass(WorkListActivity.this,DetailsWorkActivity.class);
                }else if (type==2){
                    intent.setClass(WorkListActivity.this,DbWrokActivity.class);
                }else if (type==3){
                    intent.setClass(WorkListActivity.this,DetailsWorkActivity.class);
                }
                Bundle bundle=new Bundle();
                bundle.putSerializable("work",emilList.get(position-1));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent intent;
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.searchCru:
                intent = new Intent(this, SearchActivity.class);
                startActivityForResult(intent, 1);
                break;

            case R.id.ritgh_text:
                intent = new Intent(this, AddWorkActivity.class);

                startActivity(intent);
                break;

            default:
                break;
        }
    }

    public void setRef(){
        page=1;
        emilList.clear();
        adapter.notifyDataSetChanged();
        getDate(keyword, type);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (page < allPage) {
                        page++;
                        getDate(keyword, type);
                    } else {
                        listView.setFooterName("", false);
                    }
                    break;

            }

        }
    };




    //获取工作列表列表
    private void getDate(String selstr, int type) {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId",UConstants.EmpId);
        params.addBodyParameter("Title", selstr);
//        params.addBodyParameter("Type", type + "");
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", pageSize + "");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (dowmUp){
                    onLoad();
                }
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        allPage = Integer.parseInt(object.getString("total"));
                        allPage = (int) Math.ceil((double) allPage / pageSize);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Gson gson = new Gson();
                            Type lt = new TypeToken<List<Work>>() {
                            }.getType();
                            List<Work> list = gson.fromJson(object.getString("rows").toString(), lt);
                            if (list != null && list.size() > 0) {
                                emilList.addAll(list);
                                adapter.notifyDataSetChanged();
                                if (page == allPage) {
                                    listView.setFooterName("", false);
                                } else if (page <= allPage) {
                                    listView.setFooterVisibility(true);
                                }

                            } else {
                                Toast.makeText(x.app(), "暂无工作安排！", Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(x.app(), object.getString("msg")+"", Toast.LENGTH_LONG).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    boolean dowmUp;
    @Override
    public void onRefresh() {
        dowmUp=true;
        setRef();
    }

    @Override
    public void onLoadMore() {
        handler.sendEmptyMessage(1);
        onLoad();


    }

    private void onLoad() {
        listView.stopRefresh();
        listView.stopLoadMore();
        listView.setRefreshTime("刚刚");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    keyword = data.getStringExtra("keyword");
                    emilList.clear();
                    page = 1;
                    adapter.notifyDataSetChanged();
                    getDate(keyword, 2);

                }
            }
        }

    }
}
